package com.gliese.util.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import sun.reflect.Reflection;

public class FileReaderHelper {
	public static InputStream readFromClassPath(String path) throws IOException {
		InputStream inputStream = null;
		// URL mp3Url = FileReader.class.getResource(path);
		inputStream = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(path);
		return inputStream;
	}

	public static InputStream readResourceByURL(String path) throws IOException {
		return readResourceByURL(path, null);
	}
	/**
	 * get resource(.properties)  from current package 
	 * 
	 * @param path
	 * @param clazz
	 * @return
	 * @throws IOException
	 */
	public static InputStream readResourceByURL (String path,Class clazz) throws IOException{
		if(clazz==null){
			clazz =Reflection.getCallerClass(3);
		}
		URL url = clazz.getResource(path);
		assert url == null : "check  file path (" + path + ") is right !";
		return url.openStream();
	}
	/**
	 * read file form user.home,such as "~/.xxx" in linux system.
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static InputStream readResourceByHomePath(String fileName)
			throws IOException {
		String absPath = System.getProperty("user.home")
				+ System.getProperty("file.separator") + "." + fileName;
		File file = new File(absPath);
		if (!file.exists())
			return null;
		if (file.isDirectory())
			return null;
		return new FileInputStream(file);

	}
	
}
